<?php
include_once "phplot/phplot.php";

class Lib_Phplot {
    private $CI;
    
    public function __construct() {
        $this->CI =& get_instance();
    }
    
    // vytvori graf na zaklade $data, ktore obsahuje JSON info
    public function getGraph($fk_tasks, $data) {
            $dataObj = json_decode($data);
            $task = $this->CI->tasks_model->getByIdJoined($fk_tasks);
            
            $minVal = 9999999;
            $maxVal = -9999999;
            $minX =9999999;
            $maxX = -9999999;
            
            $functions = $task->functions_count;
            $data = array();
            foreach ($dataObj as $col) {
                
                $build=array('');
                $at = 0;
                foreach ($col as $c) {
                    
                    $build[] = (float)$c;
                    if ($at == 0) {
                        if ($c < $minX)
                            $minX = $c;
                        if ($c > $maxX)
                            $maxX = $c;
                    } else {
                         if ($c < $minVal)
                            $minVal = $c;
                        if ($c > $maxVal)
                            $maxVal = $c;
                    }
                    
                    $at++;
                }
                
                if (count($build) > 1)
                  $data[] = $build;
            }
            
            
            // poziadanie - X aj Y zacinat od nuly vzdy
            if ($minX > 0)
            $minX = 0;
            
            if ($minVal > 0)
            $minVal = 0;
            
            
            $plot = new PHPlot(800, 600);
            $plot->SetImageBorderType('plain');

            $plot->SetPlotType('lines');
            $plot->SetDataType('data-data');
            $plot->SetDataValues($data);

            $legend = array();
            for ($i=1;$i<=$functions;$i++)
               $legend[] = 'f'.$i.'(x)';
            
            $plot->SetLegend($legend);

            
            $plot->SetPlotAreaWorld($minX, $minVal, $maxX, $maxVal);

            $plot->SetXDataLabelPos('none');
            $plot->SetXTickIncrement(1);
            $plot->SetXLabelType('data');
            $plot->SetPrecisionX(3);

            $plot->SetYTickIncrement(1);
            $plot->SetYLabelType('data');
            $plot->SetPrecisionY(1);

            $plot->SetDrawXGrid(True);
            $plot->SetDrawYGrid(True);
            
            $plot->DrawGraph();
    }
   
}

?>
